import tornado.auth
import tornado.escape
import tornado.web

from mixins import *

DEBUG = 10
INFO = 20
SUCCESS = 25
WARNING = 30
ERROR = 40


class BaseHandler(tornado.web.RequestHandler, SettingsMixin, MessagesMixin):
	def render_string(self, template_name, **kwargs):
		default = dict(
			page_name = self.page_name,
			upload_url=self.upload_url
		)
		kwargs.update(default)
		
		return tornado.web.RequestHandler.render_string(self, template_name, **kwargs)
	
	def xsrf_form_html(self):
		return '<input type="hidden" name="_xsrf" value="' + \
			tornado.escape.xhtml_escape(self.xsrf_token) + '">'
	
	def get_current_user(self):
		return self.get_secure_cookie('user')
	
	@property
	def db(self):
		return self.application.db
	
	@property
	def js_enabled(self):
		return bool(int(self.get_argument('_js_enabled', False)))
	
	def initialize(self, page_name):
		self.page_name = page_name
	
	def redirect_to(self, name, *args):
		location = self.reverse_url(name, *args)
		self.redirect(location)
	
	def upload_url(self, path):
		return self.static_url(os.path.join(self.settings['upload_path'], path))


class SignInHandler(BaseHandler, tornado.auth.GoogleMixin):
	@tornado.web.asynchronous
	def get(self):
		if self.get_argument('openid.mode', None):
			self.get_authenticated_user(self.async_callback(self._on_auth))
			return
		
		self.authenticate_redirect()
	
	def _on_auth(self, user):
		if not user or user['email'] not in self.settings['admin_ids']:
			logging.error("Attempted sign in with invalid account '%s'", user['email'])
			self.write(
				'Invalid account. Please sign out of Google and try again.')
			self.finish()
			return
		
		self.set_secure_cookie('user', user['email'])
		self.redirect_to('admin')


class SignOutHandler(BaseHandler):
	def post(self):
		self.clear_cookie('user')
		self.redirect('/')